#install packages
library(panelView)
library(zoo)
library(synthdid)
library(fect)
library(ggplot2)
source("staggered_synth.R")
#prepare data
laws = read.csv("statelaws.csv")
turnout = read.csv("stateturnout.csv")
laws = laws[laws$State!="",]
results <- list()

for (i in 1:nrow(laws)) {
  for (j in 2:ncol(laws)) { 
    if (!is.na(laws[i, j])) {
      if (laws[i, j] == "X") {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = TRUE)))
      }else {
        results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
      }
    }else {
      results <- c(results, list(data.frame(STATE = laws$State[i], YEAR = colnames(laws)[j], Law = FALSE)))
    }
  }
}
laws <- do.call(rbind, results)
laws$YEAR <-substring(laws$YEAR,2,10000)

data = merge(laws,turnout,by=c("STATE","YEAR"))
data = data[!(data$STATE %in%c("Texas")),]
data = data[data$YEAR != 2022&data$YEAR != 1982&data$YEAR != 1980,]
data$Y = as.numeric(gsub(",","",data$VOTE_FOR_HIGHEST_OFFICE))/as.numeric(gsub(",","",data$VEP))*100

names(data)[names(data)=="Law"] <- "W"
names(data)[names(data)=="STATE"] <- "State"
names(data)[names(data)=="YEAR"] <- "Year"


data$Unit = data$State
data$Time = data$Year
data$W = as.numeric(data$W)

#create early vs late adopting groups
data$group = as.numeric(data$State %in% c("Arizona", "Georgia", "Indiana", "Ohio")) + 2*as.numeric(data$State %in% c("Alabama", "Kansas", "Mississippi", "North Dakota", "Tennessee", "Virginia", "Wisconsin"))

data.save <- data

data[data$State == "Alabama"&data$Year == 2012,]$W =1
data[data$State == "Arizona"&data$Year == 2004,]$W =1
data[data$State == "Georgia"&data$Year == 2004,]$W =1
data[data$State == "Indiana"&data$Year == 2004,]$W =1
data[data$State == "Kansas"&data$Year == 2008,]$W =1
data[data$State == "Mississippi"&data$Year == 2012,]$W =1
data[data$State == "North Dakota"&data$Year == 2012,]$W =1
data[data$State == "Ohio"&data$Year == 2004,]$W =1
data[data$State == "Tennessee"&data$Year == 2008,]$W =1
data[data$State == "Virginia"&data$Year == 2008,]$W =1
data[data$State == "Wisconsin"&data$Year == 2012,]$W =1

data[data$State == "Alabama"&data$Year == 2008,]$W =1
data[data$State == "Arizona"&data$Year == 2000,]$W =1
data[data$State == "Georgia"&data$Year == 2000,]$W =1
data[data$State == "Indiana"&data$Year == 2000,]$W =1
data[data$State == "Kansas"&data$Year == 2004,]$W =1
data[data$State == "Mississippi"&data$Year == 2008,]$W =1
data[data$State == "North Dakota"&data$Year == 2008,]$W =1
data[data$State == "Ohio"&data$Year == 2000,]$W =1
data[data$State == "Tennessee"&data$Year == 2004,]$W =1
data[data$State == "Virginia"&data$Year == 2004,]$W =1
data[data$State == "Wisconsin"&data$Year == 2008,]$W =1
presidential_sdid_back = StaggeredSynthDiD_es(data[as.numeric(data$Year)%%4 == 0& data$State != "Virginia" & data$State != "North Dakota",],vcov="jack")
presidential_early_sdid_back <- StaggeredSynthDiD_es( data[as.numeric(data$Year)%%4 == 0& data$group != 2,],vcov="jack")
presidential_late_sdid_back <- StaggeredSynthDiD_es( data[as.numeric(data$Year)%%4 == 0& data$State != "Virginia" & data$State != "North Dakota" & data$group != 1,],vcov="jack")
data <- data.save

data[data$State == "Alabama"&data$Year == 2010,]$W =1
data[data$State == "Arizona"&data$Year == 2002,]$W =1
data[data$State == "Georgia"&data$Year == 2006,]$W =1
data[data$State == "Indiana"&data$Year == 2002,]$W =1
data[data$State == "Kansas"&data$Year == 2010,]$W =1
data[data$State == "Mississippi"&data$Year == 2010,]$W =1
data[data$State == "North Dakota"&data$Year == 2010,]$W =1
data[data$State == "Ohio"&data$Year == 2002,]$W =1
data[data$State == "Tennessee"&data$Year == 2010,]$W =1
data[data$State == "Virginia"&data$Year == 2010,]$W =1
data[data$State == "Wisconsin"&data$Year == 2014,]$W =1

data[data$State == "Alabama"&data$Year == 2006,]$W =1
data[data$State == "Arizona"&data$Year == 1998,]$W =1
data[data$State == "Georgia"&data$Year == 2002,]$W =1
data[data$State == "Indiana"&data$Year == 1998,]$W =1
data[data$State == "Kansas"&data$Year == 2006,]$W =1
data[data$State == "Mississippi"&data$Year == 2006,]$W =1
data[data$State == "North Dakota"&data$Year == 2006,]$W =1
data[data$State == "Ohio"&data$Year == 1998,]$W =1
data[data$State == "Tennessee"&data$Year == 2006,]$W =1
data[data$State == "Virginia"&data$Year == 2006,]$W =1
data[data$State == "Wisconsin"&data$Year == 2010,]$W =1

midterm_sdid_back = StaggeredSynthDiD_es(data[as.numeric(data$Year)%%4 == 2,],vcov="jack")
midterm_early_sdid_back <- StaggeredSynthDiD_es( data[as.numeric(data$Year)%%4 == 2& data$group != 2,],vcov="jack")
midterm_late_sdid_back <- StaggeredSynthDiD_es( data[as.numeric(data$Year)%%4 == 2& data$group != 1,],vcov="jack")
data <- data.save

data[data$State == "Alabama"&data$Year == 2012,]$W =1
data[data$State == "Arizona"&data$Year == 2004,]$W =1
data[data$State == "Georgia"&data$Year == 2004,]$W =1
data[data$State == "Indiana"&data$Year == 2004,]$W =1
data[data$State == "Kansas"&data$Year == 2008,]$W =1
data[data$State == "Mississippi"&data$Year == 2012,]$W =1
data[data$State == "North Dakota"&data$Year == 2012,]$W =1
data[data$State == "Ohio"&data$Year == 2004,]$W =1
data[data$State == "Tennessee"&data$Year == 2008,]$W =1
data[data$State == "Virginia"&data$Year == 2008,]$W =1
data[data$State == "Wisconsin"&data$Year == 2012,]$W =1

data[data$State == "Alabama"&data$Year == 2010,]$W =1
data[data$State == "Arizona"&data$Year == 2002,]$W =1
data[data$State == "Georgia"&data$Year == 2006,]$W =1
data[data$State == "Indiana"&data$Year == 2002,]$W =1
data[data$State == "Kansas"&data$Year == 2010,]$W =1
data[data$State == "Mississippi"&data$Year == 2010,]$W =1
data[data$State == "North Dakota"&data$Year == 2010,]$W =1
data[data$State == "Ohio"&data$Year == 2002,]$W =1
data[data$State == "Tennessee"&data$Year == 2010,]$W =1
data[data$State == "Virginia"&data$Year == 2010,]$W =1
data[data$State == "Wisconsin"&data$Year == 2014,]$W =1

all_sdid_back = StaggeredSynthDiD_es(data[data$State != "Virginia" & data$State != "North Dakota",],vcov="jack")
all_early_sdid_back <- StaggeredSynthDiD_es( data[ data$group != 2,],vcov="jack")
all_late_sdid_back <- StaggeredSynthDiD_es( data[data$State != "Virginia" & data$State != "North Dakota" & data$group != 1,],vcov="jack")





plot_event_with_weights_noshade <- function(
    sdid_x, sdid_est, sdid_se, Lambda, T_Weights, ev_grid = NULL,
    main = "", fect_x = NULL, fect_est = NULL, fect_se = NULL,
    fect_offset = -0.12, sdid_offset = +0.12,
    xlab = "Elections Relative to First Election With Strict Voter ID Law",
    ylab = "Difference in Turnout (%)",
    xlim = range(sdid_x), ylim = c(-10, 10),
    tick_by = 1                # ← new
) {
  c_fect <- "#0A8754"; c_sdid <- "#AF3B6E"
  has_fect <- !is.null(fect_est) && length(fect_est)>0
  x_seq <- sort(unique(sdid_x))
  
  # include 0 so we highlight -1 and 0
  pre_times       <- sort(unique(sdid_x[sdid_x <= 0]))
  highlight_times <- tail(pre_times, 2)
  
  plot(xlim, ylim, type="n", xlab=xlab, ylab=ylab, xaxt="n", yaxt="n")
  abline(h=0, col="gray50", lty=2); abline(v=0.5, col="gray50", lty=2)
  
  # SDID
  sd_cols <- ifelse(sdid_x %in% highlight_times, "#AF3B6E", if(has_fect) c_sdid else "black")
  points(sdid_x+sdid_offset, sdid_est, pch=15, col=sd_cols, cex=1)
  arrows(sdid_x+sdid_offset, sdid_est-1.96*sdid_se,
         sdid_x+sdid_offset, sdid_est+1.96*sdid_se,
         angle=90, code=3, length=0.04, col=sd_cols)
  
  # FEct
  if(has_fect){
    fe_cols <- ifelse(fect_x %in% highlight_times, "#AF3B6E", c_fect)
    points(fect_x+fect_offset, fect_est, pch=16, col=fe_cols, cex=1.2)
    arrows(fect_x+fect_offset, fect_est-1.96*fect_se,
           fect_x+fect_offset, fect_est+1.96*fect_se,
           angle=90, code=3, length=0.03, col=fe_cols)
    legend("topleft",
           legend=c("FEct","SDID"),
           col=c(c_fect,c_sdid), pch=c(16,15),
           bty="n", cex=1.25)
  }
  # CUSTOM X‐axis ticks
  axis(1,
       at     = seq(xlim[1], xlim[2], by = tick_by),
       labels = seq(xlim[1], xlim[2], by = tick_by))
  axis(2,
       at     = seq(ylim[1], ylim[2], by = 2),
       labels = seq(ylim[1], ylim[2], by = 2))
}
postscript("figures/backdated.eps",
           width = 14, height = 14,
           horizontal = FALSE, paper = "special")
par(oma = c(0, 1.75, 1.75, 0))

## ── grid: 3 rows × 3 cols ────────────────────────────────
## rows  = option timing        → All | Early | Late
## cols  = election type        → All | Presidential | Midterm
layout(matrix(1:9, nrow = 3, byrow = TRUE),  # order matters, see draw() list below
       widths  = c(1, 1, 1),
       heights = c(1, 1, 1))
par(mgp = c(1.5, 0.5, 0), mar = c(2.5, 2.6, 0, 1.5))

draw <- function(obj, sdid_x, xlab = "", ylab = "", tick_by = 1) {
  plot_event_with_weights_noshade(
    sdid_x    = sdid_x,
    sdid_est  = obj$Estimate,
    sdid_se   = obj$SE,
    Lambda    = obj$Lambda,
    T_Weights = obj$T_Weights,
    xlab      = xlab,
    ylab      = ylab,
    xlim      = range(sdid_x),
    ylim      = c(-12, 12),
    tick_by   = tick_by
  )
}


## ── 1) All-Cohorts row ───────────────────────────────────
draw(all_sdid_back,            sdid_x = -15:8, tick_by = 2)          # 1,1
draw(presidential_sdid_back,   sdid_x = -7:4)                        # 1,2
draw(midterm_sdid_back,        sdid_x = -7:4)                        # 1,3

## ── 2) Early-Adopters row ────────────────────────────────
draw(all_early_sdid_back,            sdid_x = -11:8, tick_by = 2)    # 2,1
draw(presidential_early_sdid_back,   sdid_x = -5:4)                  # 2,2
draw(midterm_early_sdid_back,        sdid_x = -5:4)                  # 2,3

## ── 3) Late-Adopters row ─────────────────────────────────
draw(all_late_sdid_back,            sdid_x = -15:5, tick_by = 2,     # 3,1
     xlab = "Elections Relative to First Election With Strict Voter ID Law",
     ylab = "Difference in Turnout (%)")
draw(presidential_late_sdid_back,   sdid_x = -7:3,
     xlab = "Elections Relative to First Election With Strict Voter ID Law")
draw(midterm_late_sdid_back,        sdid_x = -7:2,
     xlab = "Elections Relative to First Election With Strict Voter ID Law")

## ── column / row headers ─────────────────────────────────
mtext(c("All Election Types", "Presidential Elections", "Midterm Elections"),
      side = 3, line = 0.4, outer = TRUE,
      at = c(1/6, 3/6, 5/6), cex = 1, font = 2)

mtext(c("All Cohorts", "Early Adopters (before 2008)", "Late Adopters (after 2008)"),
      side = 2, line = 0.4, outer = TRUE,
      at = c(5/6, 3/6, 1/6), cex = 1, font = 2)

dev.off()